<template>
  <div class="load">
    <div class="loadmain" v-for="(item,index) in loadlistData" :key='index'>
      <div class="top">
        <div class="left">
          <span>配送时间</span>
        </div>
        <div class="right">
          <!-- <div class="top">
            <div class="timetab" @click="handlePrevious(dayDate)"> &lt;</div>
            {{dayDate}}
            <div class="timetab" @click='handleNextstep(dayDate)'> &gt;</div>
          </div> -->
          <div class="time">
            <div v-for='(time,index2) in item.timeSlotList' :key='index2' :class="[item.timeSlotList.length>8?'time-items':'time-item']">{{time}}</div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="left">
          <span>配送负荷</span>
        </div>
        <div class="right">
          <div class="warehouseLoadList-item" v-for='(warehouseLoad,index3) in item.warehouseLoadList' :key='index3'>
            <input class="edit-cell" type='number' v-model="warehouseLoad.params" min='0' v-if="showEdit" style='width: 40px;'
              maxlength="4">
            <span v-if="!showEdit">{{warehouseLoad.params}}</span>
          </div>
        </div>
      </div>

    </div>
    <div class="button">
      <el-button type="primary" plain @click='editLoad' size="small" v-if='buttonshowedit'>编辑</el-button>
      <el-button type="primary" plain @click="editcommitLoad" size="small" v-if='buttonshow'>提交</el-button>
      <el-button type="primary" plain @click='cancelLoad' size="small" v-if='buttonshow'>取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    updateWarehouseLoad,
    addWarehouseLoad,
    getWarehouseLoadList
  } from "@/api/warehouse"
  export default {
    props: {
      allList: {
        required: true,
        type: Object
      }
    },
    watch: {
      allList: {
        immediate: true, // 这句重要
        handler(val) {
          this.listData = val;
          this.getlist(this.dayDate);
        }
      }
    },
    data() {
      return {
        newdate: this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD")
          .toString(),
        dayDate: this.dayjs(new Date()).format("YYYY-MM-DD").toString(),
        tableData: [],
        warehouseLoad: '',
        openTimeList: [],
        warehouseLoadList: [], //仓库负荷值
        openTime: [],
        showEdit: false, //显示编辑框
        buttonshow: false,
        buttonshowedit: true,
        listData: [],
        loadlistData: [],
        dayDat: 0,
        loadstatus: 'create'
      }
    },
    methods: {
      loadValue(value) {
        console.log(value)
        value = parseInt(value);
      },
      getlist(warehouseDeliveryDate) {
        var time1 = Date.parse(warehouseDeliveryDate);
        var time2 = Date.parse(this.dayjs(new Date()).format("YYYY-MM-DD").toString());
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        const {
          id,
          deliveryStartTime,
          deliveryEndTime
        } = this.listData;
        getWarehouseLoadList({
          warehouseId: id,
          // warehouseDeliveryDate
        }).then((responense) => {
          const {
            warehouseLoadAddSonRequestList = []
          } = responense.data.data;
          if (warehouseLoadAddSonRequestList[0].timeSlotList.length === 0) {
            this.loadlistData = [];
            this.loadstatus = "create";
            const openTime = [deliveryStartTime + "-" + deliveryEndTime];
            warehouseLoadAddSonRequestList[0].timeSlotList = this.timeArea(openTime);
            this.timeArea(openTime).map(() => {
              warehouseLoadAddSonRequestList[0].warehouseLoadList.push({
                params: 0
              })
            })
            this.loadlistData = warehouseLoadAddSonRequestList;
            const requestPrams = JSON.parse(JSON.stringify(this.loadlistData))
            requestPrams.map(item => {
              item.warehouseLoadList = item.warehouseLoadList.map(child => child.params);
            })
            const requestData = {
              warehouseId: this.listData.id,
              warehouseLoadAddSonRequestList: requestPrams
            }
            addWarehouseLoad(requestData).then(() => {})
          } else {
            this.loadstatus = "update";
            const parent = [];
            const children = [];
            warehouseLoadAddSonRequestList.map(item => {
              parent.push({
                timeSlotList: item.timeSlotList,
                warehouseDeliveryDate: item.warehouseDeliveryDate,
                warehouseLoadList: children
              })
              item.warehouseLoadList.map(child => {
                children.push({
                  params: child
                })
              })
            })
            this.loadlistData = parent;
          }
        })
      },
      timeArea(openTime) {
        // let openTime = ['11:00:00 - 23:00:00'];
        let y = new Date().getFullYear();
        let m = new Date().getMonth() + 1;
        let d = new Date().getDate();
        let start = [],
          end = []; //start起始时间数组，end结束时间数组
        for (let i = 0, len = openTime.length; i < len; i++) { //将时间字符串转换成日期格式并存入开始时间数组和结束时间数组
          let [s, e] = openTime[i].split('-');
          start.push(new Date(y + '/' + m + '/' + d + ' ' + s));
          end.push(new Date(y + '/' + m + '/' + d + ' ' + e));
        }
        let list = [],
          warehouseLoadList = [];

        function formatTime(time) { //时间为个位数则补零
          return time < 10 ? '0' + time : time;
        }
        for (let i = 0, len = start.length; i < len; i++) {
          let len2 = (end[i].getTime() - start[i].getTime()) / (60 * 60 * 1000); //计算各子区间以半小时为间隔拆分后的数组长度
          for (let j = 0; j < len2; j++) {
            if (start[i].getTime() + 60 * 60 * 1000 <= end[i].getTime()) {
              //将各子区间日期按1小时递增转换为时间并存入list数组
              let ss = new Date(start[i].getTime() + 60 * 60 * 1000 * j),
                ee = new Date(start[i].getTime() + 60 * 60 * 1000 * (j + 1));
              list.push([formatTime(ss.getHours()) + ':' + formatTime(ss.getMinutes()) + ':00', formatTime(ee.getHours()) +
                ':' +
                formatTime(ee.getMinutes()) + ':00'
              ]);
              warehouseLoadList.push({
                params: '0'
              })
            }
          }
        }
        list = list.map(item => {
          return item.join('-');
        })
        return list;
      },
      // handlePrevious(item) {
      //   const newdate = this.dayjs(
      //       new Date()
      //     )
      //     .format("YYYY-MM-DD")
      //     .toString();
      //   if (item == newdate) {
      //     this.$message({
      //       showClose: true,
      //       message: "不可选择小于今天的时间",
      //       type: "warning"
      //     });
      //   } else {
      //     this.dayDate = this.dayjs(new Date()).format("YYYY-MM-DD").toString(),
      //       this.getlist(this.dayDate);
      //   }
      // },
      // handleNextstep() {
      //   this.dayDat++;
      //   if (this.dayDat >= 2) {
      //     this.dayDat = 1
      //   }
      //   this.dayDate = this.dayjs(new Date()).add(this.dayDat, 'days').format("YYYY-MM-DD").toString();
      //   this.getlist(this.dayDate);
      // },
      editLoad() {
        this.showEdit = true;
        this.buttonshow = true;
        this.buttonshowedit = false;
      },

      cancelLoad() {
        this.showEdit = false;
        this.buttonshow = false;
        this.buttonshowedit = true;
      },
      editcommitLoad() {
        const requestPrams = JSON.parse(JSON.stringify(this.loadlistData))
        requestPrams.map(item => {
          item.warehouseLoadList = item.warehouseLoadList.map(child => child.params);
        })
        const requestData = {
          warehouseId: this.listData.id,
          warehouseLoadAddSonRequestList: requestPrams
        }
        updateWarehouseLoad(requestData).then(res => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$emit('close')
          // const warehouseFrom = {
          //   // name: '', //仓库名称
          //   page: 1, //页码
          //   size: 10, //每页页码
          // };
          this.$emit('getList')
          this.buttonshowedit = true;
          this.buttonshow = false;
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        })
      },
      // AddcommitLoad() {
      //   const requestPrams = JSON.parse(JSON.stringify(this.loadlistData))
      //   requestPrams.map(item => {
      //     item.warehouseLoadList = item.warehouseLoadList.map(child => child.params);
      //   })
      //   const requestData = {
      //     warehouseId: this.listData.id,
      //     warehouseLoadAddSonRequestList: requestPrams
      //   }
      //   addWarehouseLoad(requestData).then(res => {
      //     this.$message({
      //       type: "success",
      //       message: "操作成功!"
      //     });
      //     this.$emit('close')
      //     const warehouseFrom = {
      //       // name: '', //仓库名称
      //       page: 1, //页码
      //       size: 10, //每页页码
      //     };
      //     this.$emit('getList')
      //     this.buttonshowedit = false;
      //     this.buttonshow = false;
      //     setTimeout(() => {
      //       this.listLoading = false;
      //     }, 1.5 * 1000);
      //   })
      // }
    }
  }
</script>

<style lang="scss">
  ul>li {
    list-style: none;
  }

  .load {
    .loadmain {
      border: 1px solid #ccc;
      margin-bottom: 20px;

      .top {
        display: flex;
        width: 100%;

        .left {
          line-height: 40px;
          width: 10%;
          border-right: 1px solid #ccc;
          text-align: center;
        }

        .right {
          width: 90%;

          .top {
            border-bottom: 1px solid #ccc;
            line-height: 40px;
            text-align: center;
            margin: 0 auto;
            display: block;

            .timetab {
              display: inline-block;
              cursor: pointer;
              font-size: 18px
            }
          }

          .time {
            display: flex;

            .time-item {
              width: 130px;
              border-right: 1px solid #ccc;
              height: 40px;
              text-align: center;
              box-sizing: border-box;
              line-height: 40px;
            }

            .time-items {
              width: 130px;
              word-break: keep-all;
              border-right: 1px solid #ccc;
              // height: 40px;
              // text-align: center;
              // box-sizing: border-box;
              // line-height: 40px;
            }

            &:after {
              border: none !important
            }
          }

        }
      }

      .bottom {
        border-top: 1px solid #ccc;
        border-right: 1px solid #ccc;
        display: flex;
        width: 100%;

        .left {
          line-height: 40px;
          width: 10%;
          text-align: center;
          border-right: 1px solid #ccc;
        }

        .right {
          width: 90%;
          display: flex;

          .warehouseLoadList-item {
            width: 130px;
            border-right: 1px solid #ccc;
            height: 40px;
            line-height: 40px;
            text-align: center;
            padding: 0 5px;
            box-sizing: border-box;

          }
        }
      }
    }

    .button {
      display: flex;
      align-items: center;
      margin: auto;
      width: 200px;
    }
  }
</style>
